import React, { useState, useEffect } from 'react';
import { useBookmarkStore } from '../store/bookmarkStore';
import SearchBar from '../components/SearchBar';
import CollectionManager from '../components/CollectionManager';
import SettingsPanel from '../components/SettingsPanel';

const Popup: React.FC = () => {
  const [activeTab, setActiveTab] = useState<'collections' | 'settings'>('collections');
  const { loading, error, fetchBookmarks } = useBookmarkStore();

  useEffect(() => {
    fetchBookmarks();
  }, [fetchBookmarks]);

  if (loading) {
    return (
      <div className="flex items-center justify-center h-screen">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-500"></div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="p-4 bg-red-50 text-red-500 rounded-md">
        Error: {error}
      </div>
    );
  }

  return (
    <div className="w-[400px] h-[600px] bg-gray-50">
      <div className="flex flex-col h-full">
        {/* Header */}
        <div className="bg-white border-b px-4 py-3">
          <h1 className="text-xl font-bold text-gray-900">BookMark Navigator</h1>
          <SearchBar className="mt-2" />
        </div>

        {/* Navigation */}
        <div className="bg-white border-b">
          <nav className="flex">
            <button
              onClick={() => setActiveTab('collections')}
              className={`flex-1 px-4 py-2 text-sm font-medium border-b-2 ${
                activeTab === 'collections'
                  ? 'border-primary-500 text-primary-600'
                  : 'border-transparent text-gray-500 hover:text-gray-700'
              }`}
            >
              Collections
            </button>
            <button
              onClick={() => setActiveTab('settings')}
              className={`flex-1 px-4 py-2 text-sm font-medium border-b-2 ${
                activeTab === 'settings'
                  ? 'border-primary-500 text-primary-600'
                  : 'border-transparent text-gray-500 hover:text-gray-700'
              }`}
            >
              Settings
            </button>
          </nav>
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto p-4">
          {activeTab === 'collections' ? (
            <CollectionManager />
          ) : (
            <SettingsPanel />
          )}
        </div>
      </div>
    </div>
  );
};

export default Popup;
